<template>
    <!-- 成本分析审核 -->
    <base-breadcrumb :breadcrumb="!isAudit">
        <a-card>
            <titleName title="基本信息"></titleName>
            <a-form-model
                ref="ruleForm"
                :model="form"
                :rules="rules"
                :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
            >
                <a-row :gutter="24">
                     <a-col :md="16" :sm="16">
                    <a-form-model-item label="所属单位" prop="project" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }">
                        <org-tree-select v-model="form.projectId" disabled isAutoSelectFirst checkStrictly @select="selectOrg"></org-tree-select>
                    </a-form-model-item>
                    </a-col>
                    <!-- <a-col :md="8" :sm="8">
                        <a-form-model-item label="所属分公司">
                            <SelectSubCompany
                                :isDefaultSelected="pageType == 'add'"
                                v-model="form.branchComId"
                                disabled
                            ></SelectSubCompany>
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="所属项目">
                            <SelectProject
                                :isDefaultSelected="pageType == 'add'"
                                v-model="form.projectId"
                                :form="form"
                                :isClear="id == ''"
                                keyValue="branchComId"
                                @change="getProjectSum"
                                disabled
                            ></SelectProject>
                        </a-form-model-item>
                    </a-col> -->
                    <a-col :md="8" :sm="8">
                        <a-form-model-item label="月份" prop="monthDate">
                            <a-month-picker
                                :disabled="pageType == 'look'"
                                @change="(date, dateString) => getTime(date, dateString, 'form', 'monthDate')"
                                placeholder="请选择"
                                v-model="form.monthDate"
                            ></a-month-picker>
                        </a-form-model-item>
                    </a-col>
                    <a-col span="8">
                        <a-form-model-item label="本月钢筋业主确认量（t）" prop="currentMonthSteelOwnerConfirm">
                            <BaseInputNumber
                                :disabled="pageType == 'look'"
                                :precision="2"
                                @change="changeCurrentMonthSteelOwnerConfirm"
                                v-model="form.currentMonthSteelOwnerConfirm"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col span="8">
                        <a-form-model-item label="本月钢筋实际消耗量（t）" prop="currentMonthSteelUsed">
                            <BaseInputNumber
                                @change="changeCurrentMonthSteelUsed"
                                :disabled="pageType == 'look'"
                                :precision="2"
                                v-model="form.currentMonthSteelUsed"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col span="8">
                        <a-form-model-item label="累计钢筋业主确认量（t）">
                            <BaseInputNumber disabled :precision="2" v-model="form.totalSteelOwnerConfirm" />
                        </a-form-model-item>
                    </a-col>
                    <a-col span="8">
                        <a-form-model-item label="累计钢筋消耗量（t）">
                            <BaseInputNumber disabled :precision="2" v-model="form.totalSteelUsed" />
                        </a-form-model-item>
                    </a-col>
                    <a-col span="8">
                        <a-form-model-item label="钢筋优化率（%）">
                            <BaseInputNumber disabled :precision="2" :value="form.steelOptimizeRate" />
                        </a-form-model-item>
                    </a-col>
                    <a-col v-if="pageType != 'look'" :md="24" :sm="24">
                        <a-form-model-item label="附件上传">
                            <upload-list
                                :businessCode="'BM20'"
                                :uploadArrys.sync="form.fileInfoVOList"
                                @fileArrysData="handleFileUploaded"
                                multiple
                            ></upload-list>
                        </a-form-model-item>
                    </a-col>
                    <a-col :md="24" :sm="24" v-else>
                        <a-form-model-item label="附件">
                            <file-link :fileList="form.fileInfoVOList"></file-link>
                        </a-form-model-item>
                    </a-col>
                </a-row>
            </a-form-model>
        </a-card>
        <a-card>
            <titleName title="数据填写"></titleName>
            <s-table
                ref="table"
                size="default"
                rowKey="key"
                :columns="columns"
                :data="loadData"
                :alert="true"
                show-size-changer
                show-quick-jumper
                :showPagination="false"
            >
                <span slot="cumulativeThisPeriod" slot-scope="text, record">
                    <a-input-number
                        v-if="record.enabled && pageType != 'look'"
                        style="border-color: #e4ac0b; background-color: #fff9e8; margin: -5px 0; width: 100%"
                        v-model="record.cumulativeThisPeriod"
                        placeholder="请输入"
                        @blur="change"
                        :disabled="pageType == 'look'"
                    ></a-input-number>
                    <span style="width: 100%; text-align: center" v-else>{{ text }}</span>
                </span>
            </s-table>
        </a-card>
        <div class="tool-btns page-btn-right-top" v-if="pageType != 'look'">
            <a-button
                v-if="id != '' && form.auditStatus == 'DRAFT'"
                type="danger"
                :loading="loading.DELETE"
                @click="handleSave('DELETE')"
                >删除草稿</a-button
            >
            <a-button
                v-if="form.auditStatus == 'REJECTED'"
                type="primary"
                :loading="loading.REJECTED"
                @click="handleSave('REJECTED')"
                >保存</a-button
            >
            <a-button v-else type="primary" :loading="loading.DRAFT" @click="handleSave('DRAFT')">保存草稿</a-button>
            <a-button type="primary" :loading="loading.SUBMITTED" @click="handleSave('SUBMITTED')">提交</a-button>
            <a-button type="primary" @click="handleClose">关闭</a-button>
        </div>
        <div class="tool-btns page-btn-right-top" v-else>
            <a-button type="primary" @click="handleClose">关闭</a-button>
        </div>
        <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
    </base-breadcrumb>
</template>
<script>
import { getProjectInfo } from '@/api/businessAffairs/revenueAndCost'
import {
    getCostAnalysisAuditTem,
    changeCostAnalysisAuditTem,
    addCostAnalysisAudit,
    editCostAnalysisAudit,
    delCostAnalysisAudit,
    checkCostAnalysisAudit,
    getProjectSum
} from '@/api/businessAffairs/revenueAndCost'
import { getSelectListByType } from '@/api/businessAffairs/common.js'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import { isAttachment, checkVisibleInDetail } from '@/utils/util'
import { STable } from '@/components'
import UploadList from '@/components/UploadList'
const columns = [
    {
        title: '序号',
        dataIndex: 'sortNum',
        width: '5%',
        scopedSlots: { customRender: 'sortNum' }
    },
    {
        title: '费用名称',
        dataIndex: 'name'
    },
    {
        title: '截止本期累计（元）',
        dataIndex: 'cumulativeThisPeriod',
        scopedSlots: { customRender: 'cumulativeThisPeriod' }
    },
    {
        title: '备注',
        dataIndex: 'remark'
    }
]
export default {
    name: 'a' + Date.now(),
    components: {
        SelectSubCompany,
        SelectProject,
        STable,
        UploadList
    },
    data() {
        this.columns = columns
        return {
            checkVisibleInDetail: checkVisibleInDetail(this),
            loading: {
                DELETE: false,
                DRAFT: false,
                SUBMITTED: false,
                REJECTED: false
            },
            form: {
                constructionArea: '',
                fileInfoVOList: [],
                itemList: []
            },
            key: 0,
            rules: {
                branchComId: [{ required: true, message: '请选择分公司' }],
                projectId: [{ required: true, message: '请选择项目' }],
                monthDate: [{ required: true, message: '请输入' }],
                currentMonthSteelOwnerConfirm: [{ required: true, message: '请输入' }],
                currentMonthSteelUsed: [{ required: true, message: '请输入' }]
            },
            id: '',
            timeout: '',
            pageType: '',
            spinning: false,
            ProjectSum: {},
            loadData: () => {
                if (this.form.itemList.length > 0) {
                    return new Promise((resolve, reject) => {
                        resolve({
                            data: this.form.itemList
                        })
                    })
                }
            },
            //获取流程配置值
            processConfig: null,
            //点击提交发送流程配置值
            setProcessConfig: null,
            businessId: null
        }
    },
    props: {
        isAudit: {
            // 是否作为审批详情
            type: Boolean,
            default: false
        }
    },
    watch: {
        isAudit: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.$nextTick(() => {
                        this.pageType = 'look'
                    })
                }
            }
        }
    },

    async mounted() {
        if (this.$route.query.id) {
            this.id = this.$route.query.id

            this.checkCostAnalysisAuditReq()
        }else{
            this.form.projectId = this.$userInfo().currentPost.projectId;
        }
        this.pageType = this.$route.query.pageType
        if (this.pageType == 'look') {
            this.$route.meta.title = '成本分析审核查看'
        } else {
            this.$route.meta.title = this.id == '' ? '成本分析审核新增' : '成本分析审核编辑'
        }
        if (this.pageType == 'add') {
            this.getCostAnalysisAuditTemReq()
        }
       //获取通过获取流程配置值
       this.processConfig = await this.$getConfigFn('comm_cost_analysis')
    },

    methods: {
     //选择单位
        selectOrg(val) {
            if (val && val.length) {
                this.form.branchComId = val[val.length - 2].orgId;
                this.getProjectSum(this.form.projectId)
            }
        },
        async getProjectSum(e) {
            if (this.pageType == 'look') return
            const [err, res] = await getProjectSum({ projectId: e })
            if (!err) {
                this.form = { ...this.form, ...res.data }
                this.ProjectSum = this.$clone(res.data)
                this.changeCurrentMonthSteelOwnerConfirm()
                this.changeCurrentMonthSteelUsed()
            }
        },
        changeCurrentMonthSteelOwnerConfirm() {
            console.log(this.ProjectSum)
            if (this.form.currentMonthSteelOwnerConfirm || this.form.currentMonthSteelOwnerConfirm === 0) {
                this.$nextTick(() => {
                    this.form.totalSteelOwnerConfirm =
                        this.ProjectSum.totalSteelOwnerConfirm + this.form.currentMonthSteelOwnerConfirm
                    this.form.steelOptimizeRate =
                        ((this.form.totalSteelOwnerConfirm - this.form.totalSteelUsed) /
                            this.form.totalSteelOwnerConfirm) *
                        100
                })
            }
        },
        changeCurrentMonthSteelUsed() {
            console.log(this.form)
            if (this.form.currentMonthSteelUsed || this.form.currentMonthSteelOwnerConfirm === 0) {
                this.$nextTick(() => {
                    this.form.totalSteelUsed = this.ProjectSum.totalSteelUsed + this.form.currentMonthSteelUsed
                    this.form.steelOptimizeRate =
                        ((this.form.totalSteelOwnerConfirm - this.form.totalSteelUsed) /
                            this.form.totalSteelOwnerConfirm) *
                        100
                })
            }
        },
        handleFileUploaded(list) {
            this.form.fileInfoVOList = [...list]
        },
        async getCostAnalysisAuditTemReq() {
            console.log(this.$refs.table)
            this.$refs.table.localLoading = true
            const [err, res] = await getCostAnalysisAuditTem({ type: 4, isParent: true })
            this.$refs.table.localLoading = false
            if (!err) {
                this.form.itemList = res.data

                this.$refs.table.refresh(true)
            }
        },

        getTime(date, dateString, type, name) {
            this[type][name] = dateString
            console.log(this[type][name])
        },
        async change() {
            let that = this

            if (this.timeout != '') {
                clearTimeout(this.timeout)
            }
            this.timeout = setTimeout(function () {
                that.getChangeCostAnalysisAuditTem()
            }, 1000)
        },
        async getChangeCostAnalysisAuditTem() {
            // this.$refs.table.localLoading = true
            console.log(this.form)
            const [err, res] = await changeCostAnalysisAuditTem(this.form)
            // this.$refs.table.localLoading = false
            if (!err) {
                this.form.itemList = res.data

                this.$refs.table.refresh(true)
            }
        },
        async checkCostAnalysisAuditReq() {
            this.$refs.table.localLoading = true
            const [err, res] = await checkCostAnalysisAudit({ id: this.id })
            this.$refs.table.localLoading = false
            if (!err) {
                this.form = res.data
                this.getProjectSum(this.form.projectId)
                this.$refs.table.refresh(true)
            }
        },
        validateForm() {
            let flag = false
            this.$refs.ruleForm.validate((valid) => {
                if(!valid) {
                  this.$message.warning("请填写完所有必填项信息")
                }
                flag = valid
            })
            return flag
        },
        async delCostAnalysisAudit(params) {
            const [err, res] = await delCostAnalysisAudit({ id: this.form.id })
            if (!err) {
                this.$message.success('删除成功')
                this.handleClose()
            }
        },
        // 处理增、删、改操作
        async handleSave(status) {
            this.setProcessConfig = null;
            if (this.loading[status]) return
            if (status != 'DELETE') {
                if (!this.validateForm()) return

                if (isAttachment(this, status, this.form.fileInfoVOList)) return
            }

            const params = {
                ...this.form,
                auditStatus: status
            }
            const { pageType } = this.$route.query
            const fn = pageType === 'edit' ? editCostAnalysisAudit : addCostAnalysisAudit
            const map = {
                DELETE: delCostAnalysisAudit,
                DRAFT: fn,
                SUBMITTED: fn,
                REJECTED: fn
            }
            console.log(status)
            if (status == 'DELETE') {
                let that = this
                this.$confirm({
                    title: '温馨提示',
                    content: '确定是否删除数据？',
                    okText: '确认',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk: () => {
                        return that.delCostAnalysisAudit(params)
                    }
                })
              this.loading[status] = false
            } else {
                this.loading[status] = true
                this.submitApprovalConfirm(status =='SUBMITTED'? this.processConfig:6, async (flag)=>{
                  if(!flag) {
                    this.loading[status] = false
                    return
                  }
                const [err, res] = await map[status](params)
                if (!err) {
                    if (status === 'REJECTED' || status === 'DRAFT') {
                        this.$message.success('保存成功')
                    } else {
                        this.$message.success('提交成功')
                    }
                   if(status =='SUBMITTED') {
                    //提交时，返回id
                        this.businessId = res.data.id;
                        this.setProcessConfig = this.processConfig;
                        return
                    }else{
                    this.handleClose()
                 }
                }
               this.loading[status] = false
                })
            }


        },
        handleClose() {
            if (this.isAudit) {
                window.close()
            } else {
                this.$multiTab.close(this.$route.fullpath)
            }
        }
    }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.tool-btns {
    display: flex;

    justify-content: flex-end;
    @{deep} .ant-btn + .ant-btn {
        margin-left: 12px;
    }
}
</style>
